//
//  DoorSystemHomeLvingViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/3/22.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorHomeViewController.h"
#import "DoorAlert.h"
#import "AudioPickerContentController.h"
#import "HomeContainerView.h"


#import "DoorEnginerViewController.h"
#import "DoorUserViewController.h"

#import "DoorSendCodeModel.h"
#import "RongGaoGit.h"
#import "TanChuangView.h"


#define TITLES @[@"工程设置", @"用户设置"]
#define ICONS @[@"icon_engineeringleft_nor",@"icon_userleft_nor"]



#import <IOTCamera/AVFRAMEINFO.h>
#ifdef LIB_140210
#import <IOTCamera/ImageBuffInfo.h>
#import <AVFoundation/AVFoundation.h>
#import <sys/time.h>
#import <sys/utsname.h>
#else
#import <sys/time.h>
#endif
#if defined(P2PMENBOSHI)
#define TALK_MODE_TOUCH
#endif

#if P2PNETCAM_HAIER
#define TAG_SNALSHOT_BUTTON 0
#define TAG_RECORD_BUTTON   1
#define TAG_LISTEN_BUTTON   2
#define TAG_TALK_BUTTON     3
#define TAG_QUALITY_BUTTON  4
#define TAG_FLIP_BUTTON     5
#else
#define TAG_SNALSHOT_BUTTON 0
#define TAG_RECORD_BUTTON   1
#define TAG_LISTEN_BUTTON   2
#define TAG_QUALITY_BUTTON  3
#define TAG_FLIP_BUTTON     4
#endif

#ifndef P2PAIC
#endif

//#ifdef LIB_140210
#define DEF_WAIT4STOPSHOW_TIME	250
#ifndef GET_TICK_COUNT
#define GET_TICK_COUNT
static unsigned int _getTickCount2() {
    
    struct timeval tv;
    
    if (gettimeofday(&tv, NULL) != 0)
        return 0;
    
    return (tv.tv_sec * 1000 + tv.tv_usec / 1000);
}
#endif
//#endif

#define VIEW_HD_VIDEO_QAULITY           0
#define VIEW_VIDEO_QAULITY_PRIORITY     1
#define VIEW_SMOOTH_VIDEO_PRIORITY      2

#define MAX_RECORD_TIME_SEC 60*60

#define ALERT_TAG_LOGOUT_AUTH   100
#define ALERT_TAG_UNLOCK        200


@interface DoorHomeViewController ()<MonitorTouchDelegate>{
    
    MyCamera *camera;
    NSInteger selectedChannel;
    BOOL isRecordload;
    LocalRecorder *myLocalRecorder;
    NSInteger warnOrigValue;
    TanChuangView  *tanchuangView;

#ifdef DOUBLE_AUDIO
    ENUM_AUDIO_MODE selectedAudioListenMode;
    ENUM_AUDIO_MODE selectedAudioTalkMode;
#else
    ENUM_AUDIO_MODE selectedAudioMode;
#endif
    
    int wrongPwdRetryTime;
    NSUInteger frameNewCount;
    NSUInteger frameOrigCount;
    
    NSInteger origIncompleteFrameCount;
    NSInteger origFrameCount;
    BOOL isStartRecord;
    
    NSTimer *recordingTimer;
    NSInteger recordingTimes;
    
    SystemSoundID shake_sound_male_id;
    NSInteger firstQualityOrigValue;
    NSInteger firstFlipOrigValue;
    
    BOOL selectFlipHBool;
    BOOL selectFlipVBool;
    BOOL selectUpDownBool;
    BOOL selectLeftRightBool;
    
    BOOL ptzRunning;
    
    BOOL isCancelVideoWatchDog;
    BOOL islisten;
}
@property (nonatomic, assign) BOOL bStopShowCompletedLock;



@property(nonatomic,readonly) UIDeviceOrientation orientation; // return current device orientation


@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** Count **/
@property(nonatomic,strong) NSArray *CountArray;

/** nsarry **/
@property(nonatomic,strong) NSArray *titleArray;
@end

@implementation DoorHomeViewController
#ifdef LIB_140210
@synthesize mCodecId;
@synthesize glView;
@synthesize mPixelBufferPool;
@synthesize mPixelBuffer;
@synthesize mSizePixelBuffer;

#endif
- (NSArray *)CountArray{
    
    if (!_CountArray) {
        
        _CountArray = @[@"0.25",@"0.5",@"0.75",@"1"];
    }
    return _CountArray;
}
- (IBAction)reload:(id)sender {
    
    if (camera != nil) {
        
        [camera disconnect];
        
        [camera setViewPwd:camera.viewPwd];
        [camera connect:camera.uid];
        [camera start:0];
        
        SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
        s->channel = 0;
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
        free(s);
        
        SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
        free(s2);
        
        [_loadingViewPortrait setHidden:NO];
        
        [_loadingViewPortrait startAnimating];
        
        if (selectedAudioMode == AUDIO_MODE_MICROPHONE)
            [camera startSoundToDevice:selectedChannel];
        
        if (selectedAudioMode == AUDIO_MODE_SPEAKER)
            [camera startSoundToPhone:selectedChannel];
    }
    
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    [self.monitorPortrait deattachCamera];
    if ([camera isKindOfClass:[MyCamera class]]) {
        MyCamera *cam = (MyCamera *)camera;
        cam.lastChannel = selectedChannel;
    }
    
    
    if (camera != nil) {
        [camera stopShow:selectedChannel];
        [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
        [camera stopSoundToDevice:selectedChannel];
        [camera stopSoundToPhone:selectedChannel];
        
        //[self unactiveAudioSession];
        [self unactiveAudioSession1];
        [AppDelegate globalDelegate].cameraModel.delegate2 = nil;
        
        camera = nil;
        
        [self.glView tearDownGL];
        self.glView = nil;
    }

}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager]setEnableAutoToolbar:NO];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self checkCamera];
    [self checkDoorStauts];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    
    if (camera != nil) {
        
        
        
        [self correctTimeAndTimeZone];
        
        camera.delegate2 = self;
        
#ifndef MacGulp
#endif
        [self changeOrientation:self.interfaceOrientation];
        
        [self verifyConnectionStatus];
        
        if (camera.sessionState != CONNECTION_STATE_CONNECTED)
            [camera connect:camera.uid];
        
        if ([camera getConnectionStateOfChannel:0] != CONNECTION_STATE_CONNECTED) {
            [camera start:0];
            
            SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
            s->channel = 0;
            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
            free(s);
            
            SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
            free(s2);
            
            SMsgAVIoctrlSetTimeReq *s3 = (SMsgAVIoctrlSetTimeReq *)malloc(sizeof(SMsgAVIoctrlSetTimeReq));
            s3->time_second_0zone_ = [[NSDate date] timeIntervalSince1970];
            s3->diff_zone_minites_ = [[NSTimeZone localTimeZone] secondsFromGMT] / 60;
            
            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_TIME_REQ Data:(char *)s3 DataSize:sizeof(SMsgAVIoctrlSetTimeReq)];
            free(s3);
            NSLog(@"sendIOCtrlToChannel IOTYPE_USER_IPCAM_SET_TIME_REQ(uid:%@)", camera.uid);
        }
        
#ifdef LIB_140210
        if ( selectedChannel != 0 && [camera getConnectionStateOfChannel:selectedChannel] != CONNECTION_STATE_CONNECTED) {
            [camera start:selectedChannel];
        }
        
        [camera startShow:selectedChannel ScreenObject:self];
#else
        if ([camera getConnectionStateOfChannel:selectedChannel] != CONNECTION_STATE_CONNECTED) {
            [camera start:selectedChannel];
        }
        
        [camera startShow:selectedChannel];
#endif
        [self.loadingViewPortrait setHidden:NO];
        [self.loadingViewPortrait startAnimating];
        
        
#if defined(TALK_MODE_TOUCH)
        //    [self selectListenOrTalk:1];
        selectedAudioMode = AUDIO_MODE_OFF;
        
        //isListen = YES;
#else
        
        
        [self activeAudioSession];
        
        if (selectedAudioMode == AUDIO_MODE_SPEAKER) {
            [camera startSoundToPhone:selectedChannel];
            
            self.listenButton.tintColor = [UIColor redColor];
        }
        
        if (selectedAudioMode == AUDIO_MODE_MICROPHONE) {
            [camera startSoundToDevice:selectedChannel];
            
            self.talkButton.tintColor = [UIColor redColor];
        }
#endif
        
#if defined(P2PNETCAM_HAIER)
        // Get ExternalDevices Info
        [self toGetExternalDevicesInfo];
    }
    
    self.navigationController.navigationBar.translucent = NO;
#else
}
#endif

// Get video quality
firstQualityOrigValue = -1;
[self qualitySMsgAVIoctrlGet];

// Get video flip
firstFlipOrigValue = -1;
[self flipSMsgAVIoctrlGet];

// Get warn
[self warnSMsgAVIoctrlGet];

selectFlipHBool = NO;
selectFlipVBool = NO;

ptzRunning = NO;

// Get door password mode
[self doorPasswordModeSMsgAVIoctrlGet];



frameNewCount = 0;
frameOrigCount = 0;
isCancelVideoWatchDog = NO;
#ifdef LIB_140210

#endif


}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[IQKeyboardManager sharedManager]setEnableAutoToolbar:YES];
    [tanchuangView removeFromSuperview];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(checkDoorStauts) name:@"updateTableView" object:nil];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(NotificationopenTheDoor) name:@"openTheDoor" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(NotificationcloseTheDoor) name:@"closeTheDoor" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(NotificationpauseDoor) name:@"pauseTheDoor" object:nil];
    
    [self masLayoutSubview];
}

- (void)masLayoutSubview{
    
    
    __weak typeof(self) weakself = self;
    [self.EventView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(weakself.monitorPortrait);
        
    }];
}

- (DoorEventView *)EventView{
    
    if (!_EventView) {
        
        __weak UIView *superView = self.topView;
        _EventView = [[DoorEventView alloc] init];
        [superView addSubview:_EventView];
        
    }
    
    return _EventView;
}


- (void)checkDoorStauts{
    
    DoorStatusModel *statusModel = [RongGaoGit getDoorStatusModel];
    if ([statusModel.doorLockStauts integerValue] == 0) {//1.	解锁(0开锁  1上锁)默认0
        
        [self.lockBtn setSelected:YES];
        
    }else if ([statusModel.doorLockStauts integerValue] == 1){
        
        [self.lockBtn setSelected:NO];
    }
    
    if ([statusModel.runMode integerValue] == 1) {//1手动模式  2自动模式
        
        //在自动模式下 暂停按钮 和关门按钮能点击
        self.pauseBtn.enabled = YES;
        self.closeBtn.enabled = YES;
        
    }else if ([statusModel.runMode integerValue] == 2){
        
        //在自动模式下 暂停按钮 和关门按钮不能点击
        self.pauseBtn.enabled = NO;
        self.closeBtn.enabled = NO;
    }
    
    
    
}



- (void)viewDidUnload{
    
#ifdef LIB_140210
    if(glView) {
        [self.glView tearDownGL];
        self.glView = nil;
    }
    CVPixelBufferRelease(mPixelBuffer);
    CVPixelBufferPoolRelease(mPixelBufferPool);
#endif
    
}

- (void)checkCamera
{
    
    /*  默认为门模式 此处的逻辑是首先查询本地所有的摄像头列表，如果有则判断绑定部分 */
    
    if ([AppDelegate globalDelegate].camera_list.count > 0) {
        
        for (MyCamera *camerainfo in [AppDelegate globalDelegate].camera_list) {
            
            if ([camerainfo.uid isEqualToString:EXRACT_OBJECT([AppDelegate globalDelegate].doorWiFiModel.macAddress)]) {
                
                camera = camerainfo;
                [self cameraType];
                break;
            }else{
                
                [self doorType];
            }
        }
    }else{
        
        [self doorType];
    }
    
               
}



- (void)doorType{
    
    self.callBtn.hidden = YES;
    self.monitBtn.hidden = YES;
    self.EventView.hidden = NO;
    self.monitorPortrait.hidden = YES;
}

- (void)cameraType{
    
    self.callBtn.hidden = NO;
    self.monitBtn.hidden = NO;
    self.EventView.hidden = YES;
    [self setCameraDelegate];
    self.monitorPortrait.hidden = NO;

}
                 
- (void)setCameraDelegate{
                     
    islisten = NO;
    
    
#ifdef LIB_140210
    //    selectedChannel = 0;
#else
    selectedChannel = 0;
#endif
    wrongPwdRetryTime = 0;
    // init record
    
    
    [self reload:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidBecomeActive:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    //第一次进入设置监听
    //  [self selectListenOrTalk:1];
    //Sound
    [self initSnapshotSound];
    
    
    self.loadingViewPortrait.hidesWhenStopped = YES;
    
}
                 
 
- (IBAction)lockEvent:(UIButton *)sender {
    
    [[AppDelegate globalDelegate] sendCommandByFunctionCode:@"1013" functionCommand:@"0300"];
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (sender.selected == YES) {//关
            DoorStatusModel *statusModel = [RongGaoGit getDoorStatusModel];
            if ([statusModel.doorStauts isEqualToString:@"00"]) {
                
                [[AppDelegate globalDelegate] sendCommandByFunctionCode:@"1000" functionCommand:@"0601"];
                sender.selected = !sender.selected;
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:@"请先关门"];
            }
            
        }else{//开
            
            [[AppDelegate globalDelegate] sendCommandByFunctionCode:@"1000" functionCommand:@"0600"];
            sender.selected = !sender.selected;
            
        }

    });
    
}


- (IBAction)pushSetVCEvent:(UIButton *)sender {
    [YBPopupMenu showRelyOnView:sender titles:TITLES icons:ICONS menuWidth:150 delegate:self];

}

#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
    NSLog(@"点击了 %@ 选项",TITLES[index]);
    if (index == 0) {
        
        
        
        tanchuangView = [[TanChuangView alloc]initWithFrame:self.view.bounds];
        tanchuangView.titleLabel.text = @"请输入工程密码";
        
        __weak typeof (tanchuangView)weakTanChuang = tanchuangView;
        __weak typeof(self) weakself = self;
        
        tanchuangView.pressSureBtn = ^(NSString *pwd){
            if ([pwd isEqualToString:@"1234"]) {
                [SVProgressHUD showSuccessWithStatus:@"验证密码成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakTanChuang outWithAnimation];
                });
                
                DoorEnginerViewController *vc = [[DoorEnginerViewController alloc] init];
                [weakself.navigationController pushViewController:vc animated:YES];
                
            }else{
                [SVProgressHUD showErrorWithStatus:@"密码错误"];
                
                
                [weakTanChuang outWithAnimation];
                
            }
            
            
        };
        tanchuangView.pressCancelBtn = ^(){
            weakself.tabBarController.selectedIndex = 1;
            
            [weakTanChuang outWithAnimation];
        };
        
        [[UIApplication sharedApplication].keyWindow addSubview:tanchuangView];
        
        
        
        
        
    }else if (index == 1){
        DoorUserViewController *vc = [[DoorUserViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


- (void)NotificationopenTheDoor{
    
    DoorStatusModel *statusModel = [RongGaoGit getDoorStatusModel];
    
    
    if ([statusModel.doorLockStauts integerValue] == 0) {////1.	解锁(0开锁  1上锁)默认0
        
        if ([statusModel.runMode integerValue] == 1) {//1手动模式  2自动模式
            
            
            NSString *openOffse = [NSString hexadecimalToDecimal:statusModel.openDoorDistance hexadecimalLength:4];
            
            NSString *Offse = self.CountArray[[openOffse integerValue]];
            
            [self.EventView moveLeftWithOffset:[Offse floatValue] completion:^(BOOL finished) {
                
            } duration:2.0f];
            
            
        }else if ([statusModel.runMode integerValue] == 2){
            
            NSString *time = [NSString hexadecimalToDecimal:statusModel.doorStopTime hexadecimalLength:4];
            
            [self.EventView setChangeAnimation:[time integerValue]];
            
        }

    }else{
        
        return [SVProgressHUD showInfoWithStatus:@"请先解锁平移门"];

    }
    
    
}
- (void)NotificationpauseDoor{
    
    [self.EventView stopAnimation];

}

- (void)NotificationcloseTheDoor{
    
    [self.EventView moveRightWithOffset:1 completion:^(BOOL finished) {
        
    } duration:2.0f];
}


- (IBAction)openTheDoor:(UIButton*)sender {
    
    /* 只有在自动模式下 才会有门停留时间 */
    
    DoorStatusModel *statusModel = [RongGaoGit getDoorStatusModel];
    
    
    if ([statusModel.doorLockStauts integerValue] == 1) {////1.	解锁(0开锁  1上锁)默认0
        
        return [SVProgressHUD showInfoWithStatus:@"请先解锁平移门"];
    }
    if ([statusModel.runMode integerValue] == 1) {//1手动模式  2自动模式
        
        
        NSString *openOffse = [NSString hexadecimalToDecimal:statusModel.openDoorDistance hexadecimalLength:4];
        
        NSString *Offse = self.CountArray[[openOffse integerValue]];
        
        [self.EventView moveLeftWithOffset:[Offse floatValue] completion:^(BOOL finished) {
            
        } duration:2.0f];
        
        
    }else if ([statusModel.runMode integerValue] == 2){
        
        NSString *time = [NSString hexadecimalToDecimal:statusModel.doorStopTime hexadecimalLength:4];
        
        [self.EventView setChangeAnimation:[time integerValue]];
        
    }

    [[AppDelegate globalDelegate] sendCommandByFunctionCode:@"F001" functionCommand:@"0601"];

}
- (IBAction)pauseDoor:(UIButton*)sender {
    
    [self.EventView stopAnimation];
    
    [[AppDelegate globalDelegate] sendCommandByFunctionCode:@"F001" functionCommand:@"0603"];

}
- (IBAction)closeTheDoor:(UIButton *)sender {
    
    
    [self.EventView moveRightWithOffset:1 completion:^(BOOL finished) {
        
    } duration:2.0f];

    [[AppDelegate globalDelegate] sendCommandByFunctionCode:@"F001" functionCommand:@"0602"];

}













































#pragma mark - --------------------------横竖屏部分--------------------------
- (void)deviceOrientationDidChange
{
    NSLog(@"deviceOrientationDidChange:%ld",(long)[UIDevice currentDevice].orientation);
    if ([UIDevice currentDevice].orientation == (UIDeviceOrientationFaceUp )) {
        return;
    }
    if([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait ) {
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
        
        [self orientationChange:NO];
        
        //注意： UIDeviceOrientationLandscapeLeft 与 UIInterfaceOrientationLandscapeRight
    } else if ([UIDevice currentDevice].orientation == (UIDeviceOrientationLandscapeLeft )) {
        
        [self orientationChange:YES];
        
        
    }else if ([UIDevice currentDevice].orientation == (UIDeviceOrientationLandscapeRight )) {
        //   if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft) {
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
        
        [self orientationChange:YES];
        
    }
    
}

#pragma mark - --------------------------横屏事件--------------------------
- (IBAction)ScrennLand:(UIButton *)sender {
    
    SEL selector = NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val =  UIInterfaceOrientationLandscapeRight;
    [invocation setArgument:&val atIndex:2];
    [invocation invoke];
    
    [self orientationChange:YES];
    
}


- (void)orientationChange:(BOOL)landscapeRight
{
    if (landscapeRight) {
        
        
        
    } else {
        
        
        NSLog(@"👋👋👋👋👋👋👋👋👋👋👋👋");
        
        
        [self.monitorPortrait attachCamera:camera];
        
#ifdef LIB_140210
        [self removeGLView:TRUE];
#endif
        self.view = self.portraitView;
        
#ifdef LIB_140210
        
        if( glView == nil ) {
            glView = [[CameraShowGLView alloc] initWithFrame:self.monitorPortrait.frame];
            self.glView.parentFrame = self.monitorPortrait.frame;
            [glView setMinimumGestureLength:100 MaximumVariance:50];
            glView.delegate = self;
            [glView attachCamera:camera];
        }
        else {
            [self.glView destroyFramebuffer];
            self.glView.initFrame = self.monitorPortrait.frame;
            self.glView.parentFrame = self.monitorPortrait.frame;
            self.glView.frame = self.monitorPortrait.frame;
        }
        
        [self.monitorPortrait addSubview:glView];
        
        
        if( mCodecId == MEDIA_CODEC_VIDEO_MJPEG ) {
            [self.portraitView bringSubviewToFront:self.monitorPortrait];
        }
        else {
            [self.monitorPortrait bringSubviewToFront:self.glView];
        }
#endif
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
        self.tabBarController.tabBar.hidden = NO;
        self.navigationController.navigationBar.hidden = NO;
        
    }
}



- (void)getScrennState{
    
    NSLog(@"%ld",(long)_orientation);
    
    
}

#ifdef LIB_140210

- (void)removeGLView :(BOOL)toPortrait
{
    if(glView ) {
        BOOL bRemoved = FALSE;
        if(toPortrait) {
            
            if( !bRemoved ) {
                for (UIView *subView in self.monitorPortrait.subviews) {
                    
                    if ([subView isKindOfClass:[CameraShowGLView class]]) {
                        
                        [subView removeFromSuperview];
                        NSLog( @"glView has been removed from scrollViewPortrait <OK>" );
                        //						bRemoved = TRUE;
                        break;
                    }
                }
            }
        }
        else {
            for (UIView *subView in self.monitorPortrait.subviews) {
                
                if ([subView isKindOfClass:[CameraShowGLView class]]) {
                    
                    [subView removeFromSuperview];
                    NSLog( @"glView has been removed from scrollViewPortrait <OK>" );
                    bRemoved = TRUE;
                    break;
                }
            }
            if( !bRemoved ) {
               
            }
            
        }
    }
}

- (void)changeOrientation:(UIInterfaceOrientation)orientation {
    
    NSLog(@"changeOrientation orientation=%ld", (long)orientation);
    
    if (orientation == UIInterfaceOrientationLandscapeLeft ||
        orientation == UIInterfaceOrientationLandscapeRight) {
        
        [self orientationChange:YES];
        
    }
    else {
        
        [self orientationChange:NO];
    }
    
}




#pragma mark - --------------------------查询摄像头状态--------------------------
- (void)verifyConnectionStatus
{
    

}

#pragma mark - --------------------------视频清晰度--------------------------
- (void)videoQualityChange
{
}

- (void)videoFlipChange
{
   
}

- (void)videoDelayStart:(id)isShow
{
    if (camera != nil) {
        NSLog(@"videoDelayStart");
        
        [self.loadingViewPortrait setHidden:NO];
        [self.loadingViewPortrait startAnimating];
        
        
        if ([@"YES"  isEqual: (NSString *)isShow]) {
#ifdef LIB_140210
            [camera startShow:selectedChannel ScreenObject:self];
#else
            [camera startShow:selectedChannel];
#endif
        }
    }
}


#pragma mark - Sound
- (void)initSnapshotSound
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"snapshot" ofType:@"aiff"];
    if (path) {
        shake_sound_male_id = 0;
        //注册声音到系统
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&shake_sound_male_id);
        //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
    }
}

//将UIView转成UIImage
-(UIImage *)getImageFromView:(UIView *)theView
{
    NSLog(@"getImageFromView width=%f, height=%f", theView.bounds.size.width, theView.bounds.size.height);
    //UIGraphicsBeginImageContext(theView.bounds.size);
    UIGraphicsBeginImageContextWithOptions(theView.bounds.size, YES, theView.layer.contentsScale);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)getImgSnapshotAndSave:(NSString *)imgName {
    UIImage *img = NULL;
    unsigned int codec_id = mCodecId;
    
    int size = 0;
    unsigned int w = 0, h = 0;
    char *imageFrame = (char *) malloc(MAX_IMG_BUFFER_SIZE);
    size = [camera getChannel:selectedChannel Snapshot:imageFrame DataSize:MAX_IMG_BUFFER_SIZE ImageType:&codec_id   WithImageWidth:&w ImageHeight:&h];
    if (size > 0) {
        
        img = [self getUIImage:imageFrame Width:w Height:h];
        NSLog(@"getImgSnapshotAndSave >>>>>>>>   width=%f, height=%f, size:%d", img.size.width, img.size.height, size);
        
        [self saveImageToFile:img :imgName];
        
    }
    
    free(imageFrame);
    
    return img;
}

#endif
- (void)updateToScreen:(NSValue*)pointer
{
    LPSIMAGEBUFFINFO pScreenBmpStore = (LPSIMAGEBUFFINFO)[pointer pointerValue];
    
    if (isRecordload) {
#if 0
        NSLog(@"mPixelBuffer >>>>>");
        NSLog(@"isRecordload 1");
        NSString *imgName = [NSString stringWithFormat:@"%f.jpg", [[NSDate date] timeIntervalSince1970]];
        
#if 0
        UIImage *img = [[UIImage alloc] init];
        img = [glView displayImage:pScreenBmpStore->pixelBuff];
        //img = [self getImageFromView:glView];
        NSLog(@">>>>>>>>   width=%f, height=%f", img.size.width, img.size.height);
        
        [self saveImageToFile:img :imgName];
#else
        [self getImgSnapshotAndSave:imgName];
#endif
        
        if (database != NULL) {
            if (![database executeUpdate:@"INSERT INTO snapshot(dev_uid, file_path, time) VALUES(?,?,?)", camera.uid, imgName, [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]]) {
                NSLog(@"Fail to add snapshot to database.");
            }
        }
        NSLog(@"isRecordload 2");
        isRecordload =  NO;
#else
        if(myLocalRecorder)
        {
            BOOL isRecord = YES;
            
            static int speek_times = 0;
            
            
            switch (speek_times) {
                case 0:
                    isRecord = YES;
                    break;
                case 1:
                    isRecord = NO;
                    break;
                default:
                    break;
            }
            
            NSString *devStr = [self deviceString];
            if ([devStr isEqualToString:@"iPhone 4 (A1332)"] ||
                [devStr isEqualToString:@"iPhone 4 (A1349)"] ||
                [devStr isEqualToString:@"iPhone 4S (A1387/A1431)"]) {
                
            } else {
                
                isRecord = YES;
            }
            
            
            //NSLog(@"isRecord:%d", isRecord);
            if (isRecord) {
#if 1
                dispatch_queue_t queue = dispatch_queue_create("photo_to_record", NULL);
                dispatch_async(queue, ^{
                    //NSLog(@" photo_to_record dispatch_queue_create! queue:%@", queue);
                    
                    unsigned int codec_id = mCodecId;
                    
                    int size = 0;
                    unsigned int w = 0, h = 0;
                    char *imageFrame = (char *) malloc(MAX_IMG_BUFFER_SIZE);
                    size = [camera getChannel:selectedChannel Snapshot:imageFrame DataSize:MAX_IMG_BUFFER_SIZE ImageType:&codec_id   WithImageWidth:&w ImageHeight:&h];
                    //NSLog(@"w:%d, h:%d queue:%@", w, h, queue);
#endif
                    
                    if (NO == myLocalRecorder.startRecordFlag) {
                        NSLog(@">>>>> myLocalRecorder startRecordH264__");
                        
                        NSString *fileName = [self recordBeginToSaveFileName];
                        if (fileName) {
                            NSLog(@">>>>> myLocalRecorder recordName:%@  pScreenBmpStore->nWidth:%d, pScreenBmpStore->nHeight:%d",
                                  fileName, pScreenBmpStore->nWidth, pScreenBmpStore->nHeight);
                            
                            [myLocalRecorder startRecordH264Image__:fileName VideoWidth:w VideoHeight:h];
                        }
                        
                    }
                    //NSLog(@"myLocalRecorder _didReceiveRawDataFrame width=%d, height=%d", width, height);
                    
                    //NSLog(@">>>>>>>> updateToScreen displayImage width=%d, height=%d", pScreenBmpStore->nWidth, pScreenBmpStore->nHeight);
                    
#if 1
                    if (size > 0) {
                        
                        NSString *imgName = [NSString stringWithFormat:@"%@.jpg", @"record"];
                        [self saveImageToTmpFile:[self getUIImage:imageFrame Width:w Height:h] :imgName];
                        
                        NSString *imgFullName = [self pathForTemporaryDirectoryResource:imgName];
                        
                        UIImage *img = [UIImage imageWithContentsOfFile:imgFullName];
                        if (img) {
                            [myLocalRecorder setImgFrame1:img VideoWidth:w VideoHeight:h];
                        }
                        
                        //NSLog(@" >>>>>>>> size:%d  width=%u, height=%u", size, w, h);
                        
                    }
                    
                    free(imageFrame);
                    
                    //NSLog(@" photo_to_record over! queue:%@", queue);
                    
                });
#else
                
                [myLocalRecorder displayImage:pScreenBmpStore->pixelBuff];
#endif
                
            }
            
            
            
            speek_times += 1;
            
            if (speek_times >= 2) {
                speek_times = 0;
            }
            //NSLog(@"speek_times:%d", speek_times);
            
            
        }
#endif
    } else {
        //NSLog(@"!!!!! <<<<< updateToScreen displayImage width=%d, height=%d", pScreenBmpStore->nWidth, pScreenBmpStore->nHeight);
        
    }
    
    [glView renderVideo:pScreenBmpStore->pixelBuff];
    
}


- (NSString*)deviceString
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //NSLog(@"platform: %@", platform);
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    //NSLog(@"NOTE: Unknown device type: %@", platform);
    return platform;
}


#pragma mark - MyCamera Delegate Methods

- (void)camera:(MyCamera *)camera_ _didChangeSessionStatus:(NSInteger)status
{
    if (camera_ == camera) {
        [self verifyConnectionStatus];
        
        if (status == CONNECTION_STATE_TIMEOUT) {
            
            [camera stopShow:selectedChannel];
            [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
            [camera stopSoundToDevice:selectedChannel];
            [camera stopSoundToPhone:selectedChannel];
            [camera disconnect];
            [self unactiveAudioSession];
            
            [camera connect:camera.uid];
            [camera start:0];
#ifdef LIB_140210
            [camera startShow:selectedChannel ScreenObject:self];
#else
            [camera startShow:selectedChannel];
#endif
            
            SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
            s->channel = 0;
            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
            free(s);
            
            SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
            free(s2);
            
            [self.loadingViewPortrait setHidden:NO];
            [self.loadingViewPortrait startAnimating];
            
            [self activeAudioSession];
            
            if (selectedAudioMode == AUDIO_MODE_SPEAKER) [camera startSoundToPhone:selectedChannel];
            if (selectedAudioMode == AUDIO_MODE_MICROPHONE) [camera startSoundToDevice:selectedChannel];
            
        }
    }
}

- (void)camera:(MyCamera *)camera_ _didChangeChannelStatus:(NSInteger)channel ChannelStatus:(NSInteger)status
{
    if (camera_ == camera) {
        
        if (channel == selectedChannel) {
            
            if (channel == selectedChannel) {
                
                [self verifyConnectionStatus];
                
                if (status == CONNECTION_STATE_WRONG_PASSWORD) {
                    
                    [camera stopShow:selectedChannel];
                    [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                    [camera stop:selectedChannel];
                    
                    if (wrongPwdRetryTime++ < 3) {
                        // self.statusLabel.text = NSLocalizedString(@"Wrong Password", nil);
                        // show change password dialog
                        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"密码错误" message:@"" preferredStyle:UIAlertControllerStyleAlert];
                        
                        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
                            textField.placeholder = @"请输入设备密码";
                        }];
                        __weak typeof(alertController) alere = alertController;
                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            
                            {
                                
                                
                                NSString *acc = @"admin";
                                NSString *pwd = alere.textFields.firstObject.text;
                                
                                if ([AppDelegate globalDelegate].database != NULL) {
                                    if (![[AppDelegate globalDelegate].database executeUpdate:@"UPDATE device SET view_pwd=? WHERE dev_uid=?", pwd, [AppDelegate globalDelegate].cameraModel.uid]) {
                                        NSLog(@"Fail to update device to database.");
                                    }
#ifdef ACCOUNT_MODE
                                    if (![database executeUpdate:@"UPDATE device2 SET view_pwd=? WHERE dev_uid=?", pwd, camera.uid]) {
                                        NSLog(@"Fail to update device2 to database.");
                                    }
#endif
                                }
                                
                                if (camera.sessionState != CONNECTION_STATE_CONNECTED)
                                    [camera connect:camera.uid];
                                
                                [camera setViewAcc:acc];
                                [camera setViewPwd:pwd];
                                [camera start:selectedChannel];
                                [camera startShow:selectedChannel ScreenObject:self];
                                
                                
                                [self activeAudioSession];
                                
                                if (selectedAudioMode == AUDIO_MODE_SPEAKER) {
                                    [camera startSoundToPhone:selectedChannel];
                                    
                                    
                                }
                                
                                if (selectedAudioMode == AUDIO_MODE_MICROPHONE) {
                                    [camera startSoundToDevice:selectedChannel];
                                    
                                }
                            }
                            
                            
                        }];
                        
                        [alertController addAction:cancelAction];
                        [alertController addAction:okAction];
                        [self presentViewController:alertController animated:YES completion:nil];
                        
                    }
                    
                } else if (status == CONNECTION_STATE_CONNECTED) {
                    
                    // self.statusLabel.text = NSLocalizedString(@"Connected", nil);
                    
                } else if (status == CONNECTION_STATE_CONNECTING) {
                    
                    // self.statusLabel.text = NSLocalizedString(@"Connecting...", nil);
                    
                } else if (status == CONNECTION_STATE_TIMEOUT) {
                    
                    // self.statusLabel.text = NSLocalizedString(@"Timeout", @"");
                    
                    [camera stopShow:selectedChannel];
                    [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                    [camera stopSoundToDevice:selectedChannel];
                    [camera stopSoundToPhone:selectedChannel];
                    [camera disconnect];
                    [self unactiveAudioSession];
                    
                    [camera connect:camera.uid];
                    [camera start:0];
#ifdef LIB_140210
                    [camera startShow:selectedChannel ScreenObject:self];
#else
                    [camera startShow:selectedChannel];
#endif
                    
                    SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                    s->channel = 0;
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                    free(s);
                    
                    SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
                    free(s2);
                    
                    [self.loadingViewPortrait setHidden:NO];
                    [self.loadingViewPortrait startAnimating];
                    
                    [self activeAudioSession];
                    
                    if (selectedAudioMode == AUDIO_MODE_SPEAKER) [camera startSoundToPhone:selectedChannel];
                    if (selectedAudioMode == AUDIO_MODE_MICROPHONE) [camera startSoundToDevice:selectedChannel];
                    
                } else {
                    
                    [self.loadingViewPortrait stopAnimating];
                    
                }
            }
        }
    }
}

- (void)camera:(MyCamera *)camera _didReceiveJPEGDataFrame:(const char *)imgData DataSize:(NSInteger)size
{
#if defined(LIB_140210)
    NSLog(@"LIB_140210 _didReceiveJPEGDataFrame");
#else
    
    if (isRecordload) {
        if(myLocalRecorder)
        {
            if (NO == myLocalRecorder.startRecordFlag) {
                NSLog(@">>>>> myLocalRecorder startRecordH264__");
                
                NSString *fileName = [self recordBeginToSaveFileName];
                if (fileName) {
                    NSLog(@">>>>> myLocalRecorder recordName:%@", fileName);
                    [myLocalRecorder startRecordJPEG__:fileName didReceiveRawDataFrame:(const char *)imgData DataSize:size];
                }
                
            }
            //NSLog(@"myLocalRecorder _didReceiveRawDataFrame width=%d, height=%d", width, height);
            
            [myLocalRecorder setJPEGImgFrame:imgData DataSize:size];
            
        }
    }
#endif
    [self.loadingViewPortrait stopAnimating];
}

- (void)camera:(MyCamera *)camera _didReceiveRawDataFrame:(const char *)imgData VideoWidth:(NSInteger)width VideoHeight:(NSInteger)height
{
    
#if defined(LIB_140210)
    frameNewCount++;
    
    //NSLog(@"LIB_140210 _didReceiveRawDataFrame frameNewCount:%ld  fr(unsigned long)ameOrigCount:%ld",  frameNewCount, frameOrigCount);
    
    
#if 1
    
#else
    
    if(myLocalRecorder)
    {
        if (NO == myLocalRecorder.startRecordFlag) {
            NSLog(@">>>>> myLocalRecorder startRecordH264__");
            
            NSString *fileName = [self recordBeginToSaveFileName];
            if (fileName) {
                NSLog(@">>>>> myLocalRecorder recordName:%@", fileName);
                [myLocalRecorder startRecordH264__:fileName didReceiveRawDataFrame:(const char *)imgData VideoWidth:width VideoHeight:height];
            }
            
        }
        //NSLog(@"myLocalRecorder _didReceiveRawDataFrame width=%d, height=%d", width, height);
        
        NSLog(@"_didReceiveRawDataFrame setImgFrame2 width=%ld, height=%ld", (long)width, (long)height);
        
        [myLocalRecorder setImgFrame:imgData VideoWidth:width VideoHeight:height];
    }
    
#endif
    
#else
    if (isRecordload) {
#if 0
        NSLog(@"mPixelBuffer >>>>>");
        NSLog(@"isRecordload 1");
        NSString *imgName = [NSString stringWithFormat:@"%f.jpg", [[NSDate date] timeIntervalSince1970]];
        
        UIImage *img = [self getUIImage3:imgData Width:width Height:height];
        
        [self saveImageToFile:img :imgName];
        
        if (database != NULL) {
            if (![database executeUpdate:@"INSERT INTO snapshot(dev_uid, file_path, time) VALUES(?,?,?)", camera.uid, imgName, [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]]) {
                NSLog(@"Fail to add snapshot to database.");
            }
        }
        NSLog(@"isRecordload 2");
        isRecordload =  NO;
#else
        if(myLocalRecorder)
        {
            if (NO == myLocalRecorder.startRecordFlag) {
                NSLog(@">>>>> myLocalRecorder startRecordH264__");
                
                NSString *fileName = [self recordBeginToSaveFileName];
                if (fileName) {
                    NSLog(@">>>>> myLocalRecorder recordName:%@", fileName);
                    [myLocalRecorder startRecordH264__:fileName didReceiveRawDataFrame:(const char *)imgData VideoWidth:width VideoHeight:height];
                }
                
            }
            //NSLog(@"myLocalRecorder _didReceiveRawDataFrame width=%d, height=%d", width, height);
            
            NSLog(@"_didReceiveRawDataFrame setImgFrame2 width=%d, height=%d", width, height);
            
            [myLocalRecorder setImgFrame:imgData VideoWidth:width VideoHeight:height];
        }
#endif
    }
#endif
    
    [self.loadingViewPortrait stopAnimating];
    
}

- (void)camera:(MyCamera *)camera_ _didReceiveFrameInfoWithVideoWidth:(NSInteger)videoWidth VideoHeight:(NSInteger)videoHeight VideoFPS:(NSInteger)fps VideoBPS:(NSInteger)videoBps AudioBPS:(NSInteger)audioBps OnlineNm:(NSInteger)onlineNm FrameCount:(unsigned long)frameCount IncompleteFrameCount:(unsigned long)incompleteFrameCount {
    
    if (camera_ == camera) {
#ifdef LIB_140210
        
        if( videoWidth > 1920 || videoHeight > 1080 ) {
            NSLog( @"!!!!!!!! ERROR !!!!!!!!   videoWidth:%ld, videoHeight:%ld", (long)videoWidth, (long)videoHeight);
            return;
        }
        
        
        CGSize maxZoom = CGSizeMake((videoWidth*2.0 > 1920)?1920:videoWidth*2.0, (videoHeight*2.0 > 1080)?1080:videoHeight*2.0);
        
        if (self.glView && videoWidth > 0 && videoHeight > 0 ) {
            [self recalcMonitorRect:CGSizeMake(videoWidth, videoHeight)];
            self.glView.videoSize = CGSizeMake(videoWidth, videoHeight) ;
            self.glView.frame = self.glView.frame;
            
            self.glView.maxZoom = maxZoom;
        }
        
        /*
         if( maxZoom.width / self.scrollViewPortrait.frame.size.width > 1.0 ) {
         self.scrollViewPortrait.maximumZoomScale = maxZoom.width / self.scrollViewPortrait.frame.size.width;
         }
         else {
         self.scrollViewPortrait.maximumZoomScale = 1;
         }
         */
        
#endif
        
#ifndef MacGulp
#if defined(P2PNETCAM_HAIER)
        
#else
        
        NSLog(@"%@", [NSString stringWithFormat:@"%ldx%ld / FPS: %ld / BPS: %ld Kbps", (long)videoWidth, (long)videoHeight, (long)fps, (videoBps + audioBps) / 1024]);
        
        if ((videoBps + audioBps)/1024 > 20) {
            
            
        }
        
        
        if(origIncompleteFrameCount < 0 ||
           origFrameCount < 0 ||
           origIncompleteFrameCount > incompleteFrameCount ||
           origFrameCount > frameCount) {
            
            origIncompleteFrameCount = incompleteFrameCount;
            origFrameCount = frameCount;
            
        } else {
            double interIncompleteFrameCount = 0.0;
            double interFrameCount = 0.0;
            double perIncomplete = 0.0;
            
            interIncompleteFrameCount = incompleteFrameCount - origIncompleteFrameCount;
            interFrameCount = frameCount - origFrameCount;
            if(interFrameCount > 0) {
                perIncomplete = (interIncompleteFrameCount / interFrameCount);
                
                if(perIncomplete < 0.25) {
                    //self.signalImageView.image = [UIImage imageNamed:@"d-signal-4.png"];
                    //                    self.signalInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Viewing Status:Good", @"")];
                } else if(perIncomplete >= 0.25 && perIncomplete < 0.5) {
                    //self.signalImageView.image = [UIImage imageNamed:@"d-signal-4.png"];
                    //                    self.signalInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Viewing Status:Good", @"")];
                } else if(perIncomplete >= 0.5 && perIncomplete < 0.75) {
                    //self.signalImageView.image = [UIImage imageNamed:@"d-signal-2.png"];
                    //                    self.signalInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Viewing Status:General", @"")];
                } else if(perIncomplete >= 0.75) {
                    //self.signalImageView.image = [UIImage imageNamed:@"d-signal-1.png"];
                    //                    self.signalInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Viewing Status:Bad", @"")];
                }
            } else {
                //self.signalImageView.image = [UIImage imageNamed:@"d-signal-1.png"];
                //                self.signalInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Viewing Status:Bad", @"")];
            }
            
            origIncompleteFrameCount = incompleteFrameCount;
            origFrameCount = frameCount;
        }
        //NSLog(@"%@", [NSString stringWithFormat:@"%dx%d", videoWidth, videoHeight]);
#endif
#else
        
        if (onlineNm >= 5) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CAM P" message:NSLocalizedString(@"Exceed multiple viewer limitation", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
            [alert show];
            [alert release];
            
            [camera stopShow:selectedChannel];
            [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
            [camera stopSoundToDevice:selectedChannel];
            [camera stopSoundToPhone:selectedChannel];
            
            self.monitorPortrait.image = nil;
            self.monitorLandscape.image = nil;
            
            self.videoInfoLabel.text = [NSString stringWithFormat:@"%dx%d @ %d fps", videoWidth, videoHeight, 0];
            self.frameInfoLabel.text = [NSString stringWithFormat:@"x%d", onlineNm];
        }
        else {
            self.videoInfoLabel.text = [NSString stringWithFormat:@"%dx%d @ %d fps", videoWidth, videoHeight, fps];
            self.frameInfoLabel.text = [NSString stringWithFormat:@"x%d", onlineNm];
        }
#endif
    }
}


- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    
    NSLog(@"_didReceiveIOCtrlWithType type:%ld(%lx)", (long)type, (long)type);
    
#if defined(P2PNETCAM_HAIER)
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_GET_EXTERNAL_DEVICES_RESP) {
        
        SMsgAVIoctrlGetCameraExternalDevicesParamsResp *structExternalDevicesParams = (SMsgAVIoctrlGetCameraExternalDevicesParamsResp*)data;
        
        switch (structExternalDevicesParams->params) {
            case AVIOTC_EXTERNAL_DEVICES_TEMPERATURE:
                self.temperature.text = [[NSString alloc] initWithFormat:@"%.2f", structExternalDevicesParams->value];
                break;
            case AVIOTC_EXTERNAL_DEVICES_RELATIVE_HUMIDITY:
                self.humidity.text = [[NSString alloc] initWithFormat:@"%.2f", structExternalDevicesParams->value];
                break;
            case AVIOTC_EXTERNAL_DEVICES_FORMALDEHYDE:
                self.formaldehyde.text = [[NSString alloc] initWithFormat:@"%.2f", structExternalDevicesParams->value];
                break;
            case AVIOTC_EXTERNAL_DEVICES_PARTICULATE_MATTER25:
                self.pm25.text = [[NSString alloc] initWithFormat:@"%.2f", structExternalDevicesParams->value];
                break;
            default:
                break;
        }
    }
#endif
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_GETSTREAMCTRL_RESP) {
        
        SMsgAVIoctrlGetStreamCtrlResq *s = (SMsgAVIoctrlGetStreamCtrlResq*) data;
        //self.qualityOrigValue = [self qualityDeviceToView:s->quality];
        
        if (firstQualityOrigValue == -1) {
            firstQualityOrigValue = [self qualityDeviceToView:s->quality];
            
            [self changeQualityViewStatus:NO];
        }
        
        NSLog(@"==================================== s->quality:%d  firstQualityOrigValue:%d",
              s->quality, firstQualityOrigValue);
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_GET_VIDEOMODE_RESP) {
        
        SMsgAVIoctrlGetVideoModeResp *s = (SMsgAVIoctrlGetVideoModeResp*)data;
        //self.flipOrigValue = s->mode;
        
        if (firstFlipOrigValue == -1) {
            firstFlipOrigValue = s->mode;
        }
        
        NSLog(@"==================================== s->mode%d  firstFlipOrigValue:%d",
              s->mode, firstFlipOrigValue);
        
        [self changeFlipViewStatus];
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_SET_IRCUT_RESP) {
        SMsgAVIoctrlSetIrcutModeResp *s = (SMsgAVIoctrlSetIrcutModeResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_SET_IRCUT_RESP s->result:%d", s->result);
        if (0 == s->result) {
            // [[iToast makeText:NSLocalizedString(@"IR Correct Success", @"")]show];
        } else {
            //  [[iToast makeText:NSLocalizedString(@"IR Correct Fail", @"")]show];
        }
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_SET_TIME_RESP) {
        SMsgAVIoctrlSetTimeResp *s = (SMsgAVIoctrlSetTimeResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_SET_TIME_RESP s->result:%d",
              s->result);
        
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_GET_DOOR_STATUS_RESP) {
        SMsgAVIoctrlGetDoorStatusResp *s = (SMsgAVIoctrlGetDoorStatusResp *)data;
        NSLog(@"GetDoorStatus s->door1:%d, s->door2:%d", s->door1, s->door2);
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_SET_DOOR_STATUS_RESP) {
        SMsgAVIoctrlSetDoorStatusResp *s = (SMsgAVIoctrlSetDoorStatusResp *)data;
        NSLog(@"SetDoorStatus s->door1:%d, s->door2:%d", s->door1, s->door2);
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_GET_DOORPASSWORDMODE_RESP) {
        SMsgAVIoctrlGetDoorPasswordModeResp *s = (SMsgAVIoctrlGetDoorPasswordModeResp *)data;
      
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_SET_DOORPASSWORDMODE_RESP) {
    }
    
    if (camera_ == camera && type == IOTYPE_USER_IPCAM_SET_DOORPASSWORD_RESP) {
    }
    
    if (type == IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP) {
        SMsgAVIoctrlThirdpartResp *s = (SMsgAVIoctrlThirdpartResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP s->command_types_:%d, s->result_:%d, s->value_:%d",
              s->command_types_, s->result_, s->value_);
        if (THIRD_PART_GET_WARNING_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Success", @"")]show];
            
            
            
        } else if (THIRD_PART_SET_WARNING_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Fail", @"")]show];
            
            
        }
    }
    
}
- (void)changeQualityViewStatus:(BOOL)isMessage
{
}

- (void)changeFlipViewStatus
{
       /*
     switch (value) {
     case AVIOCTRL_VIDEOMODE_NORMAL:
     #if defined(STYLE_ORANGE_AIC)
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h_.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v_.png"] forState:UIControlStateNormal];
     #else
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v.png"] forState:UIControlStateNormal];
     #endif
     
     [self.flipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_on.png"] forState:UIControlStateNormal];
     [self.fullFlipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_on.png"] forState:UIControlStateNormal];
     break;
     case AVIOCTRL_VIDEOMODE_FLIP:
     #if defined(STYLE_ORANGE_AIC)
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h_.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v.png"] forState:UIControlStateNormal];
     #else
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v_.png"] forState:UIControlStateNormal];
     #endif
     [self.flipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_on.png"] forState:UIControlStateNormal];
     [self.fullFlipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_on.png"] forState:UIControlStateNormal];
     break;
     case AVIOCTRL_VIDEOMODE_MIRROR:
     #if defined(STYLE_ORANGE_AIC)
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v_.png"] forState:UIControlStateNormal];
     #else
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h_.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v.png"] forState:UIControlStateNormal];
     #endif
     [self.flipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_off.png"] forState:UIControlStateNormal];
     [self.fullFlipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_off.png"] forState:UIControlStateNormal];
     break;
     case AVIOCTRL_VIDEOMODE_FLIP_MIRROR:
     #if defined(STYLE_ORANGE_AIC)
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v.png"] forState:UIControlStateNormal];
     #else
     [self.fullPageMoreFlipHButton setBackgroundImage:[UIImage imageNamed:@"_flip-h_.png"] forState:UIControlStateNormal];
     [self.fullPageMoreFlipVButton setBackgroundImage:[UIImage imageNamed:@"_flip-v_.png"] forState:UIControlStateNormal];
     #endif
     
     [self.flipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_off.png"] forState:UIControlStateNormal];
     [self.fullFlipButton setBackgroundImage:[UIImage imageNamed:@"nex_daoche_off.png"] forState:UIControlStateNormal];
     break;
     default:
     
     break;
     }
     */
}



- (void)glFrameSize:(NSArray*)param
{
    //NSLog( @"glview:%@", self.glView);
    
    CGSize* pglFrameSize_Original = (CGSize*)[(NSValue*)[param objectAtIndex:0] pointerValue];
    CGSize* pglFrameSize_Scaling = (CGSize*)[(NSValue*)[param objectAtIndex:1] pointerValue];
    
    [self recalcMonitorRect:*pglFrameSize_Original];
    
    self.glView.maxZoom = CGSizeMake( (pglFrameSize_Original->width*2.0 > 1920)?1920:pglFrameSize_Original->width*2.0, (pglFrameSize_Original->height*2.0 > 1080)?1080:pglFrameSize_Original->height*2.0 );
    
    CGSize size = self.glView.frame.size;
    float fScale  = [[UIScreen mainScreen] scale];
    size.height *= fScale;
    size.width *= fScale;
    *pglFrameSize_Scaling = size ;
    
    
    
    if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
        self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        //        [self.scrollViewLandscape setContentSize:self.glView.frame.size];
    }
    else {
        // [self.scrollViewPortrait setContentSize:self.glView.frame.size];
    }
}

- (void)reportCodecId:(NSValue*)pointer
{
    unsigned short *pnCodecId = (unsigned short *)[pointer pointerValue];
    
    self.mCodecId = *pnCodecId;
    
    if(self.mCodecId == MEDIA_CODEC_VIDEO_MJPEG ) {
        if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
            self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            
            //            [self.scrollViewLandscape bringSubviewToFront:monitorLandscape/*self.glView*/];
        }
        else {
            //            [self.scrollViewPortrait bringSubviewToFront:monitorLandscape/*self.glView*/];
        }
    }
    else {
        if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
            self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            
            //            [self.scrollViewLandscape bringSubviewToFront:/*monitorLandscape*/self.glView];
        }
        else {
            [self.monitorPortrait bringSubviewToFront:/*monitorLandscape*/self.glView];
        }
    }
}



#pragma mark - --------------------------等待加载⌛️--------------------------

- (void)waitStopShowCompleted:(unsigned int)uTimeOutInMs
{
    unsigned int uStart = _getTickCount2();
    while( self.bStopShowCompletedLock == FALSE ) {
        usleep(1000);
        unsigned int now = _getTickCount2();
        if( now - uStart >= uTimeOutInMs ) {
            NSLog( @"CameraLiveViewController - waitStopShowCompleted !!!TIMEOUT!!!" );
            break;
        }
    }
    
}

- (void)cameraStopShowCompleted:(NSNotification *)notification
{
    _bStopShowCompletedLock = TRUE;
}

- (void)cameraStartShow:(NSTimer*)theTimer
{
#ifdef LIB_140210
    [camera startShow:selectedChannel ScreenObject:self];
#else
    [camera startShow:selectedChannel];
#endif
    
    [self.loadingViewPortrait setHidden:NO];
    [self.loadingViewPortrait startAnimating];
    
    [self activeAudioSession];
    
    if (selectedAudioMode == AUDIO_MODE_SPEAKER) [camera startSoundToPhone:selectedChannel];
    if (selectedAudioMode == AUDIO_MODE_MICROPHONE) [camera startSoundToDevice:selectedChannel];
}

- (void)snapshotToRecord {
    char *imageFrame = (char *) malloc(MAX_IMG_BUFFER_SIZE);
    unsigned int w = 0, h = 0;
#ifdef LIB_140210
    unsigned int codec_id = mCodecId;
    int size = 0;
#else
    unsigned int codec_id;
    unsigned int size = 0;
#endif
    size = [camera getChannel:selectedChannel Snapshot:imageFrame DataSize:MAX_IMG_BUFFER_SIZE ImageType:&codec_id   WithImageWidth:&w ImageHeight:&h];
    if (size > 0) {
        //NSString *imgName = [NSString stringWithFormat:@"%f.jpg", [[NSDate date] timeIntervalSince1970]];
        //UIImage *img = NULL;
        
        if (codec_id == MEDIA_CODEC_VIDEO_H264 || codec_id == MEDIA_CODEC_VIDEO_MPEG4) {
            NSLog(@"codec_id == MEDIA_CODEC_VIDEO_H264 || codec_id == MEDIA_CODEC_VIDEO_MPEG4 codec_id=%d", codec_id);
            //img = [self getUIImage:imageFrame Width:w Height:h];
            //[self saveImageToFile:img :imgName];
        }
        else if (codec_id == MEDIA_CODEC_VIDEO_MJPEG) {
            NSLog(@"codec_id == MEDIA_CODEC_VIDEO_MJPEG");
            //NSData *data = [[NSData alloc] initWithBytes:imageFrame length:size];
            //img = [[UIImage alloc] initWithData:data];
            //[self saveImageToFile:img :imgName];
            //[data release];
            //[img release];
        }
        
        if (isRecordload) {
#if 0
            NSLog(@"isRecordload 1");
            //CIImage *ciImage = [[CIImage alloc] initWithCVPixelBuffer:mPixelBuffer];
            //UIImage *image= [UIImage imageWithCIImage:ciImage];//:newImage scale:1.0  orientation:UIImageOrientationRight];
            NSString *imgName = [NSString stringWithFormat:@"%f.jpg", [[NSDate date] timeIntervalSince1970]];
            
            UIImage *img = [self getUIImage:imageFrame Width:w Height:h];
            
            [self saveImageToFile:img :imgName];
            
            if (database != NULL) {
                if (![database executeUpdate:@"INSERT INTO snapshot(dev_uid, file_path, time) VALUES(?,?,?)", camera.uid, imgName, [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]]) {
                    NSLog(@"Fail to add snapshot to database.");
                }
            }
            NSLog(@"isRecordload 2");
            isRecordload =  NO;
#else
            
            
            if (isRecordload) {
                if(myLocalRecorder)
                {
                    /*
                     if (NO == myLocalRecorder.startRecordFlag) {
                     NSLog(@">>>>> myLocalRecorder startRecordH264__");
                     
                     NSString *fileName = [self recordBeginToSaveFileName];
                     if (fileName) {
                     NSLog(@">>>>> myLocalRecorder recordName:%@", fileName);
                     [myLocalRecorder startRecordJPEG__:fileName didReceiveRawDataFrame:(const char *)imageFrame DataSize:size];
                     }
                     
                     }
                     //NSLog(@"myLocalRecorder _didReceiveRawDataFrame width=%d, height=%d", width, height);
                     
                     [myLocalRecorder setJPEGImgFrame:imageFrame DataSize:size];
                     */
                    
                    
                    if (NO == myLocalRecorder.startRecordFlag) {
                        NSLog(@">>>>> myLocalRecorder startRecordH264__");
                        
                        NSString *fileName = [self recordBeginToSaveFileName];
                        if (fileName) {
                            NSLog(@">>>>> myLocalRecorder recordName:%@", fileName);
                            [myLocalRecorder startRecordH264__:fileName didReceiveRawDataFrame:imageFrame VideoWidth:w VideoHeight:h];
                        }
                        
                    }
                    //NSLog(@"myLocalRecorder _didReceiveRawDataFrame width=%d, height=%d", width, height);
                    [myLocalRecorder setImgFrame0:imageFrame VideoWidth:w VideoHeight:h];
                    
                    
                    
                }
            }
#endif
        }
        
    }
    
    free(imageFrame);
}


#pragma mark - --------------------------画面加载重要⚠️--------------------------
- (void)recalcMonitorRect:(CGSize)videoframe
{
    CGFloat fRatioFrame = videoframe.width / videoframe.height;
    CGFloat fRatioMonitor;
    UIScrollView* viewMonitor;
    UIView* viewCanvas;
    
    
    fRatioMonitor = viewMonitor.frame.size.width/viewMonitor.frame.size.height;
    
    if( fRatioMonitor < fRatioFrame ) {
        CGFloat canvas_height = (viewMonitor.frame.size.width * viewMonitor.zoomScale) / fRatioFrame;
        
        if( canvas_height < viewMonitor.frame.size.height ) {
            viewCanvas.frame = CGRectMake(0, ((viewMonitor.frame.size.height) - canvas_height)/2.0, (viewMonitor.frame.size.width * viewMonitor.zoomScale), canvas_height);
        }
        else {
            viewCanvas.frame = CGRectMake(0, 0, (viewMonitor.frame.size.width * viewMonitor.zoomScale), canvas_height);
        }
    }
    else {
        CGFloat canvas_width = (viewMonitor.frame.size.height * viewMonitor.zoomScale) * fRatioFrame;
        
        if( canvas_width < viewMonitor.frame.size.width ) {
            viewCanvas.frame = CGRectMake(((viewMonitor.frame.size.width) - canvas_width)/2.0, 0, canvas_width, (viewMonitor.frame.size.height * viewMonitor.zoomScale));
        }
        else {
            viewCanvas.frame = CGRectMake(0, 0, canvas_width, (viewMonitor.frame.size.height * viewMonitor.zoomScale));
        }
    }
#pragma mark - --------------------------旋转--------------------------
    
    if( self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
       self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && UIInterfaceOrientationIsLandscape(self.interfaceOrientation) ) {
            CGFloat fTmp = screenRect.size.height;
            screenRect.size.height = screenRect.size.width;
            screenRect.size.width = fTmp;
        }
        CGFloat screenWidth = screenRect.size.width;
        CGFloat screenHeight = screenRect.size.height;
        
        screenRect.size.height =screenWidth ;
        screenRect.size.width = screenHeight;
        

    }
    else {
        self.glView.parentFrame = CGRectMake(0, 0, SCREEN_WIDTH, self.monitorPortrait.frame.size.height);
        self.glView.frame = CGRectMake(0, 0, SCREEN_WIDTH,self.monitorPortrait.frame.size.height);
    }
    
    
    
}

#pragma mark - --------------------------返回事件--------------------------

- (IBAction)backVCEvent:(id)sender {
    [self onLeftButtonClick:nil];

}



- (void)onLeftButtonClick:(id)sender{
    /* save last frame to local storage */
    
    
    [self.monitorPortrait deattachCamera];
    if ([camera isKindOfClass:[MyCamera class]]) {
        MyCamera *cam = (MyCamera *)camera;
        cam.lastChannel = selectedChannel;
    }
    
    
    if (camera != nil) {
        [camera stopShow:selectedChannel];
        [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
        [camera stopSoundToDevice:selectedChannel];
        [camera stopSoundToPhone:selectedChannel];
        
        //[self unactiveAudioSession];
        [self unactiveAudioSession1];
        
        camera = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - --------------------------thumbnailImageForVideo--------------------------
- (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 1) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    return thumbnailImage;
}


#pragma mark - --------------------------按钮事件--------------------------
#pragma mark - 拍照
- (IBAction)landSnapshot:(id)sender {
    [self snapshot:nil];
}
- (IBAction)portraitSnapshot:(id)sender {
    [self snapshot:nil];
}
- (void)snapshot:(UIButton *)sender {
    
    char *imageFrame = (char *) malloc(MAX_IMG_BUFFER_SIZE);
    unsigned int w = 0, h = 0;
#ifdef LIB_140210
    unsigned int codec_id = self.mCodecId;
    int size = 0;
#else
    unsigned int codec_id;
    unsigned int size = 0;
#endif
    size = [camera getChannel:selectedChannel Snapshot:imageFrame DataSize:MAX_IMG_BUFFER_SIZE ImageType:&codec_id   WithImageWidth:&w ImageHeight:&h];
    if (size > 0) {
        NSString *imgName = [NSString stringWithFormat:@"%f.jpg", [[NSDate date] timeIntervalSince1970]];
        UIImage *img = NULL;
        
        if (codec_id == MEDIA_CODEC_VIDEO_H264 || codec_id == MEDIA_CODEC_VIDEO_MPEG4) {
            img = [self getUIImage:imageFrame Width:w Height:h];
            [self saveImageToFile:img :imgName];
            
            if ([AppDelegate globalDelegate].database != NULL) {
                if (![[AppDelegate globalDelegate].database executeUpdate:@"INSERT INTO snapshot(dev_uid, file_path, time) VALUES(?,?,?)", [AppDelegate globalDelegate].cameraModel.uid, imgName, [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]]) {
                    NSLog(@"Fail to add snapshot to database.");
                }
            }
            AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
            NSLog(@"AudioServicesPlaySystemSound shake_sound_male_id");
            //            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
            
        }
        else if (codec_id == MEDIA_CODEC_VIDEO_MJPEG) {
            NSData *data = [[NSData alloc] initWithBytes:imageFrame length:size];
            img = [[UIImage alloc] initWithData:data];
            [self saveImageToFile:img :imgName];
            
            
            if ([AppDelegate globalDelegate].database != NULL) {
                if (![[AppDelegate globalDelegate].database executeUpdate:@"INSERT INTO snapshot(dev_uid, file_path, time) VALUES(?,?,?)", [AppDelegate globalDelegate].cameraModel.uid, imgName, [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]]) {
                    NSLog(@"Fail to add snapshot to database.");
                }
            }
            AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
            NSLog(@"AudioServicesPlaySystemSound shake_sound_male_id");
            //            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
            
        }
    }
    
}

#pragma mark - 通话 Down
- (IBAction)portraitTalk:(UIButton *)sender {
    [self selectListenOrTalk:2];

}
- (IBAction)talkButtonCancel:(UIButton *)sender {
    [self selectListenOrTalk:1];

}

- (void)selectTalk:(UIButton *)sender {
    
    if ([self getIsRecvAudioFormat:camera]) {
        
    } else {
        NSLog(@"selectTalk getIsRecvAudioFormat == NO; return!");
        return;
    }
    
#if defined(TALK_MODE_TOUCH)
    NSLog(@"selectTalk selectedAudioMode:%d", selectedAudioMode);
    if (selectedAudioMode == AUDIO_MODE_SPEAKER) {
        [self selectListenOrTalk:0];
    } else {
        [self selectListenOrTalk:1];
    }
#else
    NSLog(@"selectTalk selectedAudioMode:%d", selectedAudioMode);
    if (selectedAudioMode == AUDIO_MODE_MICROPHONE) {
        [self selectListenOrTalk:0];
    } else {
        [self selectListenOrTalk:2];
    }
#endif
    
}


#pragma mark - 报警


- (void)selectAlarm:(UIButton *)sender {
    
    
}
#pragma mark - --------------------------报警状态改变--------------------------
- (void)changeWarnViewStatus:(BOOL)isMessage
{
}

#pragma mark - 监听
                 
- (IBAction)portraitListen:(UIButton *)sender {

    [self selectListen:nil];

}



- (void)selectListen:(UIButton *)sender {
    
    NSLog(@"selectListen selectedAudioMode:%d", selectedAudioMode);
    if (selectedAudioMode == AUDIO_MODE_SPEAKER) {
        
        [self selectListenOrTalk:0];
        
    } else {
        
        [self selectListenOrTalk:1];
        
    }
    
}

#pragma mark - --------------------------通话部分--------------------------
- (void)selectListenOrTalk:(NSInteger)index{
    int mode = -1;
    
    if ([camera getAudioInSupportOfChannel:selectedChannel] && [camera getAudioOutSupportOfChannel:selectedChannel]) {
        
        if (index == 0) {
            
            mode = 0;
            
        } else if (index == 1) { // Device to Phone
            
            mode = 1;
            
        } else if (index == 2) { // Phone to Device
            
            mode = 2;
            
        }
        
    } else if ([camera getAudioInSupportOfChannel:selectedChannel] && ![camera getAudioOutSupportOfChannel:selectedChannel]) {
        
        if (index == 0) {
            
            mode = 0;
            
        } else if (index == 1) { // Device to Phone
            
            mode = 1;
            
        }
        
    } else if (![camera getAudioInSupportOfChannel:selectedChannel] && [camera getAudioOutSupportOfChannel:selectedChannel]) {
        
        if (index == 0) {
            
            mode = 0;
            
        } else if (index == 1) { // Phone to Device
            
            mode = 2;
            
        }
        
    } else {
        
        mode = 0;
        
    }
    
    NSLog(@"selectListenOrTalk mode:%d", mode);
    
    if (mode == 0) {//没有任何状态
        
        if (camera != nil) {
            
            selectedAudioMode = AUDIO_MODE_OFF;
            
            double delayInSeconds = 500.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_MSEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [camera stopSoundToDevice:selectedChannel];
                [camera stopSoundToPhone:selectedChannel];
            });
            
            
            [self unactiveAudioSession];
            
            [self.monitBtn setSelected:NO];
            [SVProgressHUD showInfoWithStatus:@"静音"];
            islisten = NO;
            
#if defined(P2PNETCAM_HAIER)
#else
            
#endif
        }
        
    } else if (mode == 1) { // Device to Phone
        
        if (camera != nil) {
            
 
            selectedAudioMode = AUDIO_MODE_SPEAKER;
            [SVProgressHUD showInfoWithStatus:@"监听中"];
            [self.monitBtn setSelected:YES];

            [camera stopSoundToDevice:selectedChannel];
            
            [self unactiveAudioSession];
            [self activeAudioSession];
            
            double delayInSeconds = 500.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_MSEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [camera startSoundToPhone:selectedChannel];
            });
            
#if defined(P2PNETCAM_HAIER)
#else
            
#endif
        }
        
    } else if (mode == 2) { // Phone to Device
        
        if (camera != nil) {
    
            selectedAudioMode = AUDIO_MODE_MICROPHONE;
            [SVProgressHUD showWithStatus:@"通话中"];
            [camera stopSoundToPhone:selectedChannel];
            [self.monitBtn setSelected:NO];
            [self unactiveAudioSession];
            [self activeAudioSession];
            
            double delayInSeconds = 500.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_MSEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [camera startSoundToDevice:selectedChannel];
            });
            
            
#if defined(P2PNETCAM_HAIER)
#else
            
            
#endif
            
        }
    }
}
#pragma mark - AudioSession implementations
- (void)activeAudioSession
{
#if 0
    OSStatus error;
    
    UInt32 category = kAudioSessionCategory_LiveAudio;
    
    if (selectedAudioMode == AUDIO_MODE_SPEAKER) {
        category = kAudioSessionCategory_LiveAudio;
        NSLog(@"kAudioSessionCategory_LiveAudio");
    }
    
    if (selectedAudioMode == AUDIO_MODE_MICROPHONE) {
        category = kAudioSessionCategory_PlayAndRecord;
        NSLog(@"kAudioSessionCategory_PlayAndRecord");
    }
    
    error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
    if (error) printf("couldn't set audio category!");
    
    error = AudioSessionSetActive(true);
    if (error) printf("AudioSessionSetActive (true) failed");
#else
    
    NSString *audioMode = nil;
    if (selectedAudioMode == AUDIO_MODE_SPEAKER) {
        NSLog(@"kAudioSessionCategory_LiveAudio");
        audioMode = AVAudioSessionCategoryPlayback;
    }
    
    else if (selectedAudioMode == AUDIO_MODE_MICROPHONE) {;
        NSLog(@"kAudioSessionCategory_PlayAndRecord");
        audioMode = AVAudioSessionCategoryPlayAndRecord;
    }
    
    if ( nil == audioMode){
        return ;
    }
    
    //get your app's audioSession singleton object
    AVAudioSession* session = [AVAudioSession sharedInstance];
    
    //error handling
    BOOL success;
    NSError* error;
    
    //set the audioSession category.
    //Needs to be Record or PlayAndRecord to use audioRouteOverride:
    
    success = [session setCategory:audioMode error:&error];
    
    if (!success)  NSLog(@"AVAudioSession error setting category:%@",error);
    
    //set the audioSession override
    success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
                                         error:&error];
    if (!success)  NSLog(@"AVAudioSession error overrideOutputAudioPort:%@",error);
    
    //activate the audio session
    success = [session setActive:YES error:&error];
    if (!success) NSLog(@"AVAudioSession error activating: %@",error);
    else NSLog(@"audioSession active");
    
    
#endif
}

- (void)unactiveAudioSession {
    return ;
#if 0
    AudioSessionSetActive(false);
#else
    BOOL success;
    NSError* error;
    
    //get your app's audioSession singleton object
    AVAudioSession* session = [AVAudioSession sharedInstance];
    
    //activate the audio session
    success = [session setActive:NO error:&error];
    
    if (!success) {
        NSLog(@"AVAudioSession error deactivating: %@",error);
    } else {
        NSLog(@"audioSession deactive");
    }
    
#endif
}

- (void)unactiveAudioSession1 {
#if 0
    AudioSessionSetActive(false);
#else
    BOOL success;
    NSError* error;
    
    //get your app's audioSession singleton object
    AVAudioSession* session = [AVAudioSession sharedInstance];
    
    //activate the audio session
    success = [session setActive:NO error:&error];
    
    if (!success) {
        NSLog(@"AVAudioSession error deactivating: %@",error);
    } else {
        NSLog(@"audioSession deactive");
    }
    
#endif
}


- (BOOL)getIsRecvAudioFormat:(MyCamera *)cam {
    BOOL isRecvAudioFormat = NO;
    
#if defined(AUDIO_TO_SUPPORT)
    if (cam) {
        if (cam.sessionState == CONNECTION_STATE_CONNECTED) {
            
            isRecvAudioFormat = cam.isRecvAudioFormat;
            
            if (isRecvAudioFormat) {
            } else {
                NSLog(@"IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ");
                
                SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                s->channel = 0;
                [cam sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                free(s);
            }
        }
    }
    
#endif
    NSLog(@"CameraLiveViewControllerMenboshi isRecvAudioFormat:%d", isRecvAudioFormat);
    
    
    return isRecvAudioFormat;
}

#pragma mark - --------------------------录像部分--------------------------
- (void)recordRunning
{
   
}
- (void)recordCompleted
{
    
  
}

- (void)recordDestroy
{
    
}

- (void)recordStop
{
 
}

- (void)recordStart
{
    
}

- (void)recordInit
{
}

- (void)toRecordInit
{
}

- (void)recordUnInit
{
  
}

- (void)doRecordTest
{
    [self toRecordInit];
    [self recordStart];
}

- (NSString *)recordBeginToSaveFileName
{
    NSString *videoName = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    
    if ([AppDelegate globalDelegate].database != NULL) {
        if (![[AppDelegate globalDelegate].database executeUpdate:@"INSERT INTO record(dev_uid, file_path, time) VALUES(?,?,?)", [AppDelegate globalDelegate].cameraModel.uid, videoName, [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]]) {
            NSLog(@"Fail to add record to database.");
            
            return nil;
        }
    }
    
    return videoName;
}

#pragma mark - --------------------------指令部分--------------------------
#pragma mark - 获取开锁密码
- (void)doorPasswordModeSMsgAVIoctrlGet
{
}
#pragma mark - 开锁
- (void)doorStatusSMsgAVIoctrlSet:(NSInteger)status doorPwd:(NSString *)doorpassword
{
}

- (void)doorStatusSMsgAVIoctrlGet
{
}

#pragma mark - get warn
- (void)warnSMsgAVIoctrlGet
{
    SMsgAVIoctrlThirdpartReq *g = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(g, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    g->command_types_ = THIRD_PART_GET_WARNING_STATUS;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)g
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    free(g);
}
#pragma mark - set warn
- (void)warnSMsgAVIoctrlSet
{
    
}

#pragma mark - local time and time-zone (phone to device)
- (void)correctTimeAndTimeZone {
    
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    NSLog(@"destinationTimeZone:%@",[destinationTimeZone description]);
    NSLog(@"[destinationTimeZone secondsFromGMT]:%d",[destinationTimeZone secondsFromGMT]);
    
    
    NSDate *now = [NSDate date];
    NSLog(@"NSDate now:%@",[now description]);
    
    NSTimeInterval timeInterval = [now timeIntervalSince1970];
    NSLog(@"timeInterval:%.2f", timeInterval);
    
    SMsgAVIoctrlSetTimeReq *s = (SMsgAVIoctrlSetTimeReq *)malloc(sizeof(SMsgAVIoctrlSetTimeReq));
    s->time_second_0zone_ = [[NSDate date] timeIntervalSince1970];
    s->diff_zone_minites_ = [[NSTimeZone localTimeZone] secondsFromGMT] / 60;
    
    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_TIME_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlSetTimeReq)];
    free(s);
    NSLog(@"sendIOCtrlToChannel IOTYPE_USER_IPCAM_SET_TIME_REQ(uid:%@)", camera.uid);
}

#pragma mark - get set video quality and flip
- (void)qualitySMsgAVIoctrlGet
{
    // get video quality
    SMsgAVIoctrlGetStreamCtrlReq *structVideoQuality = (SMsgAVIoctrlGetStreamCtrlReq *)malloc(sizeof(SMsgAVIoctrlGetStreamCtrlReq));
    memset(structVideoQuality, 0, sizeof(SMsgAVIoctrlGetStreamCtrlReq));
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GETSTREAMCTRL_REQ
                           Data:(char *)structVideoQuality
                       DataSize:sizeof(SMsgAVIoctrlGetStreamCtrlReq)];
    free(structVideoQuality);
}

- (void)qualitySMsgAVIoctrlSet
{
    
}

- (void)flipSMsgAVIoctrlGet
{
    // get video flip
    SMsgAVIoctrlGetVideoModeReq *structVideoFlip = (SMsgAVIoctrlGetVideoModeReq *)malloc(sizeof(SMsgAVIoctrlGetVideoModeReq));
    memset(structVideoFlip, 0, sizeof(SMsgAVIoctrlGetVideoModeReq));
    structVideoFlip->channel = 0;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_GET_VIDEOMODE_REQ
                           Data:(char *)structVideoFlip
                       DataSize:sizeof(SMsgAVIoctrlGetVideoModeReq)];
    free(structVideoFlip);
    
}

- (void)flipSMsgAVIoctrlSet
{
   
}

#pragma mark - Conversion Quality Methods

- (NSInteger)qualityDeviceToView:(NSInteger) _quality{
    NSInteger r_quality;
    
    switch (_quality) {
        case AVIOCTRL_QUALITY_UNKNOWN:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
        case AVIOCTRL_QUALITY_MAX:
            r_quality = VIEW_HD_VIDEO_QAULITY;
            break;
        case AVIOCTRL_QUALITY_HIGH:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
        case AVIOCTRL_QUALITY_MIDDLE:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
        case AVIOCTRL_QUALITY_LOW:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
        case AVIOCTRL_QUALITY_MIN:
            r_quality = VIEW_SMOOTH_VIDEO_PRIORITY;
            break;
        default:
            r_quality = VIEW_VIDEO_QAULITY_PRIORITY;
            break;
    }
    
    return r_quality;
}

- (NSInteger)qualityViewToDevice:(NSInteger) _quality{
    NSInteger r_quality;
    
    switch (_quality) {
        case VIEW_HD_VIDEO_QAULITY:
            r_quality = AVIOCTRL_QUALITY_MAX;
            break;
        case VIEW_VIDEO_QAULITY_PRIORITY:
            r_quality = AVIOCTRL_QUALITY_MIDDLE;
            break;
        case VIEW_SMOOTH_VIDEO_PRIORITY:
            r_quality = AVIOCTRL_QUALITY_MIN;
            break;
        default:
            r_quality = AVIOCTRL_QUALITY_MIDDLE;
            break;
    }
    
    return r_quality;
}

#pragma mark - --------------------------图片保存部分--------------------------
- (CGRect)zoomRectForScrollView:(UIScrollView *)_scrollView withScale:(float)scale withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    // The zoom rect is in the content view's coordinates.
    // At a zoom scale of 1.0, it would be the size of the
    // imageScrollView's bounds.
    // As the zoom scale decreases, so more content is visible,
    // the size of the rect grows.
    zoomRect.size.height = _scrollView.frame.size.height / scale;
    zoomRect.size.width  = _scrollView.frame.size.width  / scale;
    
    // choose an origin so as to get the right center.
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}

- (UIImage *)getUIImage:(char *)buff Width:(NSInteger)width Height:(NSInteger)height {
    
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buff, width * height * 3, NULL);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = CGImageCreate(width, height, 8, 24, width * 3, colorSpace, kCGBitmapByteOrderDefault, provider, NULL, true,  kCGRenderingIntentDefault);
    
    
    UIImage *img = [UIImage imageWithCGImage:imgRef];
    
    
    if (imgRef != nil) {
        CGImageRelease(imgRef);
        imgRef = nil;
    }
    
    if (colorSpace != nil) {
        CGColorSpaceRelease(colorSpace);
        colorSpace = nil;
    }
    
    if (provider != nil) {
        CGDataProviderRelease(provider);
        provider = nil;
    }
    
    return [img copy];
}

- (UIImage *) getUIImage2:(char *)buff Width:(NSInteger)width Height:(NSInteger)height {
    
#if 0
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buff, width * height * 3, NULL);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = CGImageCreate(width, height, 8, 24, width * 3, colorSpace, kCGBitmapByteOrderDefault, provider, NULL, true,  kCGRenderingIntentDefault);
    
#else
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (const unsigned char *) buff, width * height * 3,kCFAllocatorNull);
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(data);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = CGImageCreate(width, height, 8, 32, width * 4, colorSpace, bitmapInfo, provider, NULL, YES, kCGRenderingIntentDefault);
    
#endif
    
    
    UIImage *img = [UIImage imageWithCGImage:imgRef];
    
    
    if (imgRef != nil) {
        CGImageRelease(imgRef);
        imgRef = nil;
    }
    
    if (colorSpace != nil) {
        CGColorSpaceRelease(colorSpace);
        colorSpace = nil;
    }
    
    if (provider != nil) {
        CGDataProviderRelease(provider);
        provider = nil;
    }
    
    return [img copy];
}

- (UIImage *) getUIImage3:(const char *)buff Width:(NSInteger)width Height:(NSInteger)height {
    
#if 0
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buff, width * height * 3, NULL);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = CGImageCreate(width, height, 8, 24, width * 3, colorSpace, kCGBitmapByteOrderDefault, provider, NULL, true,  kCGRenderingIntentDefault);
    
#else
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (const unsigned char *) buff, width * height * 3,kCFAllocatorNull);
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(data);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = CGImageCreate(width, height, 8, 24, width * 3, colorSpace, bitmapInfo, provider, NULL, YES, kCGRenderingIntentDefault);
    
#endif
    
    
    UIImage *img = [UIImage imageWithCGImage:imgRef];
    
    
    if (imgRef != nil) {
        CGImageRelease(imgRef);
        imgRef = nil;
    }
    
    if (colorSpace != nil) {
        CGColorSpaceRelease(colorSpace);
        colorSpace = nil;
    }
    
    if (provider != nil) {
        CGDataProviderRelease(provider);
        provider = nil;
    }
    
    return [img copy];
}


- (NSString *) pathForDocumentsResource:(NSString *) relativePath {
    
    static NSString* documentsPath = nil;
    
    if (nil == documentsPath) {
        
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    
    return [documentsPath stringByAppendingPathComponent:relativePath];
}


- (NSString *) pathForTemporaryDirectoryResource:(NSString *) relativePath {
    
    static NSString* tmpDir = nil;
    
    if (nil == tmpDir) {
        
        tmpDir =  NSTemporaryDirectory();
    }
    
    return [tmpDir stringByAppendingPathComponent:relativePath];
}

- (void)saveImageToFile:(UIImage *)image :(NSString *)fileName {
    
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0f);
    
    NSString *imgFullName = [self pathForDocumentsResource:fileName];
    
    [imgData writeToFile:imgFullName atomically:YES];
}

- (void)saveImageToTmpFile:(UIImage *)image :(NSString *)fileName {
    
    NSData *imgData = UIImageJPEGRepresentation(image, 0.2f);
    
    NSString *imgFullName = [self pathForTemporaryDirectoryResource:fileName];
    
    [imgData writeToFile:imgFullName atomically:NO];
}

- (NSString *)directoryPath {
    
    if (!directoryPath) {
        
        //directoryPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Library"];
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        directoryPath = [dirs objectAtIndex:0];
    }
    return directoryPath;
}


#pragma mark - --------------------------WATCHDOG--------------------------

#ifdef LIB_140210
- (void)videoWatchDog {
    dispatch_queue_t queue = dispatch_queue_create("video_watchdog", NULL);
    dispatch_async(queue, ^{
        NSLog(@"video_watchdog dispatch_queue_create begin!");
        
        for (unsigned int k=0; NO==isCancelVideoWatchDog; k++) {
            if (frameNewCount > 0) {
                break;
            }
            
            usleep(500*1000);
            NSLog(@"frameNewCount == 0 usleep   k:%d", k);
        }
        
        NSLog(@"video_watchdog dispatch_queue_create really begin!!!");
        
        NSInteger loopMaxCount = 4; // 4*500*1000
        NSInteger loopCount = 0;
        for (unsigned int i=0; NO==isCancelVideoWatchDog; i++) {
            
            for (unsigned int j=0; NO==isCancelVideoWatchDog; j++) {
                if (frameNewCount > 0) {
                    break;
                }
                
                // 2sec
                if (j>4) {
                    NSLog(@"videoWatchDog doing------------->>>>>>>>> 2222222222");
                    
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [camera stopShow:selectedChannel];
                        
                        [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                        
                        [camera startShow:selectedChannel ScreenObject:self];
                        
                    });
                    
                    
                    frameNewCount = 0;
                    frameOrigCount = 0;
                    
                    j = 0;
                }
                
                usleep(500*1000);
                NSLog(@"frameNewCount == 0 usleep   j:%d", j);
            }
            
            usleep(500*1000);
            loopCount++;
            
            // 2 sec
            if (loopCount >= loopMaxCount) {
                loopCount = 0;
                
                //NSLog(@"videoWatchDog frameNewCount:%ld, frameOrigCount:%ld", (unsigned long)frameNewCount, (unsigned long)frameOrigCount);
                if (frameOrigCount == frameNewCount) {
                    NSLog(@"frameOrigCount == frameNewCount    videoWatchDog doing------------->>>>>>>>>");
                    
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [camera stopShow:selectedChannel];
                        
                        [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                        
                        [camera startShow:selectedChannel ScreenObject:self];
                    });
                    
                    
                    frameNewCount = 0;
                    frameOrigCount = 0;
                    
                }
                
                frameOrigCount = frameNewCount;
                
            }
        }
        
        
        NSLog(@"video_watchdog dispatch_queue_create over!");
    });
}
#endif


- (void)applicationDidBecomeActive:(NSNotification *)notification
{
#ifdef LIB_140210
    [camera startShow:selectedChannel ScreenObject:self];
#else
    [camera startShow:selectedChannel];
#endif
    if (selectedAudioMode == AUDIO_MODE_MICROPHONE)
        [camera startSoundToDevice:selectedChannel];
    if (selectedAudioMode == AUDIO_MODE_SPEAKER)
        [camera startSoundToPhone:selectedChannel];
}

#pragma mark - UIApplication Delegate
- (void)applicationWillResignActive:(NSNotification *)notification
{
    [camera stopShow:selectedChannel];
    [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
    [camera stopSoundToDevice:selectedChannel];
    [camera stopSoundToPhone:selectedChannel];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


            
@end
